# -*- coding: utf-8 -*-
# @Time    : 2019/11/4 15:07
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : yield_from_example.py

final_result = {}


# def middle(key):
#     # 委托生成器，接受商品的名称
#     while True:
#         final_result[key] = yield from sales_num(key)  # 将子生成器和调用方生成双向通信通道
#         print(key + "销量统计完成！")
#
#
# # 需求，商品和销量，利用生成器，将结果形式进行改变
# def main():
#     # 调用方
#     data_sets = {
#         "苹果手机": [1200, 1500, 3000],
#         "御泥坊面膜": [28, 55, 98, 108],
#         "恒源祥毛衣": [280, 560, 778, 70],
#     }
#     for key, data_set in data_sets.items():
#         print("start key", key)
#         m = middle(key)  # 委托生成器
#         m.send(None)  # 预激middle协程，启动生成器
#         for value in data_set:  # [1200, 1500, 3000]
#             m.send(value)  # 利用委托生成器的双向通道将值发送到子生成器中
#         m.send(None)  # 终止子生成器
#         print("final_result:", final_result)

def sales_num(pro_num):
    # 子生成器，接受商品名称
    total = 0
    nums = []
    while True:
        x = yield  # 利用委托生成器的双向通道接受调用方传入的值
        print(pro_num + "销量:", x)
        if not x:
            break
        total += x
        nums.append(x)
    return total, nums  # 返回到final_result[key] = yield from sales_num(key)


if __name__ == '__main__':
    my_gen = sales_num("苹果手机")
    my_gen.send(None)
    my_gen.send(1200)
    my_gen.send(1500)
    my_gen.send(3000)
    try:
        my_gen.send(None)
    except StopIteration as e:  # 合理的异常
        res = e.value
        print(res)
